package the.workshop.milktea.interfaces.controller;

import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.wisteria.framework.util.DateUtils;
import org.wisteria.framework.web.APIResult;
import org.wisteria.framework.web.QueryResult;
import the.broccoli.auth.UserContext;
import the.workshop.milktea.interfaces.req.FirmwareAddReq;
import the.workshop.milktea.interfaces.req.FirmwareModifyReq;
import the.workshop.milktea.interfaces.req.FirmwarePageReq;
import the.workshop.milktea.interfaces.req.FirmwareRemoveReq;
import the.workshop.milktea.interfaces.resp.FirmwareGetResp;
import the.workshop.milktea.service.FirmwareService;
import the.workshop.milktea.service.dto.FirmwareAddDTO;
import the.workshop.milktea.service.dto.FirmwareGetDTO;
import the.workshop.milktea.service.dto.FirmwareModifyDTO;
import the.workshop.milktea.service.dto.FirmwarePageDTO;

import javax.annotation.Resource;
import java.util.List;

@Api(tags = "Tea")
@RestController
@RequestMapping("/milktea/firmware")
public class FirmwareController {

    @Resource
    private FirmwareService firmwareService;

    @PostMapping("/add")
    public APIResult<Boolean> add(@RequestBody FirmwareAddReq req) {
        FirmwareAddDTO dto = new FirmwareAddDTO();
        BeanUtils.copyProperties(req, dto);
        dto.setOperatorId(UserContext.userId());
        dto.setOperatorName(UserContext.userName());
        return APIResult.success(firmwareService.add(dto));
    }

    @PostMapping("/modify")
    public APIResult<Boolean> modify(@RequestBody FirmwareModifyReq req) {
        FirmwareModifyDTO dto = new FirmwareModifyDTO();
        BeanUtils.copyProperties(req, dto);
        dto.setOperatorId(UserContext.userId());
        dto.setOperatorName(UserContext.userName());
        return APIResult.success(firmwareService.modify(dto));
    }

    @PostMapping("/remove")
    public APIResult<Boolean> remove(@RequestBody FirmwareRemoveReq req) {
        firmwareService.removeByIds(req.getIds(), UserContext.userId(), UserContext.userName());
        return APIResult.success();
    }

    @GetMapping("/page")
    public APIResult<QueryResult> page(FirmwarePageReq req) {
        FirmwarePageDTO dto  = new FirmwarePageDTO();
        BeanUtils.copyProperties(req, dto);
        QueryResult queryResult = firmwareService.pageList(dto, req.getPageNum(), req.getPageSize());
        return APIResult.success(queryResult);
    }

    @GetMapping("/{id}")
    public APIResult<FirmwareGetResp> get(@PathVariable(value = "id") Integer id) {
        FirmwareGetResp resp = null;
        FirmwareGetDTO dto = firmwareService.get(id);
        if (dto != null) {
            resp = new FirmwareGetResp();
            BeanUtils.copyProperties(dto, resp);
            resp.setUpdateTime(DateUtils.formatDate(dto.getUpdateTime()));
        }
        return APIResult.success(resp);
    }
}
